import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
import TodoList from '../views/TodoList.vue'
import Login from '../views/Login.vue' // 新增登录页面
import Profile from '../views/Profile.vue' // 新增个人资料页
import store from '../store' // 引入Vuex store

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'AboutPage',
        component: About
    },
    {
        path: '/todolist',
        name: 'TodoList',
        component: TodoList,
        meta: { requiresAuth: true }
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/profile',
        name: 'Profile',
        component: Profile,
        meta: { requiresAuth: true } // 需要登录
    }
]

const router = new VueRouter({
    mode: 'hash',
    routes
})

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
    // 检查目标路由是否需要认证
    if (to.matched.some(record => record.meta.requiresAuth)) {
        // 检查用户是否已登录
        if (!store.state.auth.isAuthenticated) {
            // 未登录则跳转到登录页，并携带原目标路径
            next({
                name: 'Login',
                query: { redirect: to.fullPath }
            })
        } else {
            next() // 已登录则放行
        }
    } else {
        next() // 不需要认证的路由直接放行
    }
})

export default router